package com.laf.model;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author: He Changjie  on  2018-10-01
 * @description:
 */
public class Base64 {
    /**
     * 图片转base64字符串
     * @param imgFile 图片路径
     * @return
     */
    public static String imageToBase64Str(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }


    /**
     * 将base64字符串转化成图片
     * @param base64 base64码
     * @param path 存储图片的路径
     * @return 转化成功返回文件名，若失败则返回null
     */
    public static String GenerateImage(String base64,String path)
    {
        if (base64 == null || base64.trim().length()==0) {
            return null;
        }
        path=path.replaceAll("\\\\","\\\\\\\\");
        //获取图片后缀
        String suffix=base64.substring(base64.indexOf("/")+1,base64.indexOf(";"));
        //生成图片全名称
        String fileName = System.currentTimeMillis() + "."+suffix;
        //裁剪base64码
        base64=base64.substring(base64.indexOf(",")+1);

        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(base64);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(path+fileName);
            out.write(b);
            out.flush();
            out.close();
            return fileName;
        }
        catch (Exception e)
        {
            return null;
        }
    }

}
